#include "timer.h"

Timer::Timer():
inializedM(false)
{
}

bool Timer::initialize()
{
    inializedM = true;
    return true;
}

bool Timer::unintialize()
{
    inializedM = false;
    return true;
}

bool Timer::queue(uint32_t timeIntvl, TimerElementInterface *element)
{
    if ( timeIntvl == 0 || element == NULL )
    {
        return false;
    }
    
    if ( elements_.find(element) == elements_.end() )
    {

        elements_.insert(TimerType::value_type(element, (timeIntvl * perSecond)));
    }
    else
    {
        TimerType::iterator it = elements_.find(element);
        it->second = (timeIntvl * perSecond);
    }
    return true;
}

bool Timer::dequeue(TimerElementInterface *element)
{
    if ( element == NULL )
    {
        return false;
    }

    if ( elements_.find(element) == elements_.end() )
        return false;

    elements_.erase(element);
    return true;

}
bool Timer::intializeState()
{
    return inializedM;
}


void Timer::handleTick()
{
    for ( TimerType::iterator it = elements_.begin(); it != elements_.end(); )
    {
        it->second--;
        if ( it->second == 0 )
        {
            TimerElementInterface *hook = it->first;
            elements_.erase(it++);

            if ( hook != NULL ) 
            {
                hook->TimeOutCallBack();
            }
        }
        else
        {
            it++;
        }
    }
}
